package logic

import (
	"context"
	"fmt"
	"weipinghui/models/cache"
	"weipinghui/models/mysql"
	"weipinghui/models/pkg"

	"weipinghui/weipinghuirpc/internal/svc"
	"weipinghui/weipinghuirpc/weipinghuirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PasswordUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPasswordUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PasswordUpdateLogic {
	return &PasswordUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PasswordUpdateLogic) PasswordUpdate(in *weipinghuirpc.PasswordUpdateRequest) (*weipinghuirpc.PasswordUpdateResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当前账号不存在，禁止修改密码")
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误，请重新输入")
	}
	if in.NewPassword != in.AckPassword {
		return nil, fmt.Errorf("两次密码不一致，请重新输入")
	}
	if in.NewPassword == in.Password {
		return nil, fmt.Errorf("新密码与旧密码一致，禁止修改")
	}
	in.Password = pkg.Md5(in.NewPassword)
	mysql.DB.Updates(&user)
	smsCode := cache.RedisDB.Get(l.ctx, "sendSms"+in.Mobile)
	if smsCode.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	return &weipinghuirpc.PasswordUpdateResponse{
		Id: int64(user.ID),
	}, nil
}
